package dongze.com.ckdj.dagger;

import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.google.gson.JsonNull;

import javax.inject.Inject;

import dongze.com.ckdj.util.MyLog;

/**
 * Created by fanqwz on 2017/9/27.
 */

public class DataStore {
    private static final String TAG = DataStore.class.getSimpleName();
    SharedPreferences sp;
    Gson gson;

    @Inject
    public DataStore(SharedPreferences sp, Gson gson) {
        this.sp = sp;
        this.gson = gson;
    }

    public <T> void set(Class<T> tClass, T data) {
        sp.edit()
                .putString(tClass.getCanonicalName(), gson.toJson(data))
                .apply();

        MyLog.v(TAG, "set:" + tClass.getCanonicalName() + ", " + gson.toJson(data));
    }

    public void clear() {
        MyLog.v(TAG, "clear");
        sp.edit().clear();
    }

    public <T> T get (Class<T> tClass) throws Exception {
        T t = gson.fromJson(sp.getString(tClass.getCanonicalName(), gson.toJson(JsonNull.INSTANCE)), tClass);
        MyLog.v(TAG, "get:" + tClass.getCanonicalName() + " = " + t);
        if (t == null)
            throw new Exception("数据异常");

        return t;
    }
}
